`
https://leetcode.cn/problems/binary-tree-right-side-view/
`

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function (root) {
  const res = []
  if (!root) return res
  const q = [root]

  while (q.length) {
    const sz = q.length

    // 每层的第一个结点就是每层最右边的结点
    res.push(q[0].val)

    // 从右到左层序遍历
    for (let i = 0; i < sz; i++) {
      const cur = q.shift()

      // 先放入右子节点，再放入左子节点
      if (cur.right) q.push(cur.right)
      if (cur.left) q.push(cur.left)
    }
  }

  return res
};